#include "WifiAsyncConnect.h"

static AsyncTimer wifiTimer;

WifiAsyncConnect::WifiInfo WifiAsyncConnect::wifi_arr[ARRAY_SIZE] = WIFI_ARRAY;
bool WifiAsyncConnect::is_wifi_open = false;
bool WifiAsyncConnect::is_all_wifi_checked = false;
bool WifiAsyncConnect::is_wifi_success = false;
bool WifiAsyncConnect::is_finished = false;
unsigned short WifiAsyncConnect::timer_id = 0;
uint8_t WifiAsyncConnect::current_wifi = 0;
uint8_t WifiAsyncConnect::count = 0;
bool WifiAsyncConnect::is_timer_checked = false;

WifiAsyncConnect::WifiAsyncConnect() {
    set_wifi_check_callback();
}

void WifiAsyncConnect::callback() {
    if (!is_all_wifi_checked) {
        if (!is_wifi_open) {
            is_wifi_open = true;
            WiFiClass::mode(WIFI_STA);
            Serial.println("wifi open");
        }

        if (!wifi_arr[current_wifi].is_begin) {
            wifi_arr[current_wifi].is_begin = true;
            #ifdef STATIC_IP
            if (wifi_arr[current_wifi].is_static_ip) {
                IPAddress IP(STATIC_IP);
                IPAddress NETMASK(STATIC_NETMASK);
                IPAddress NETWORK(STATIC_NETWORK);
                IPAddress DNS(STATIC_DNS);
                WiFi.config(IP, NETWORK, NETMASK, DNS);
            }
            #endif
            WiFi.begin(wifi_arr[current_wifi].ssid, wifi_arr[current_wifi].pass);
            Serial.print("wifi begin connect to ");
            Serial.print(wifi_arr[current_wifi].ssid);
        }

        if (WiFiClass::status() == WL_CONNECTED) {
            is_all_wifi_checked = true;
            is_wifi_success = true;
        } else {
            Serial.print(".");
            count++;
            if (count > MAX_WIFI_TRY_TIMES) {
                Serial.println("over trying times");
                current_wifi++;
                count = 0;
                if (current_wifi > ARRAY_SIZE - 1) is_all_wifi_checked = true;
            }
        }
    }
}

void WifiAsyncConnect::set_wifi_check_callback() {
    timer_id = wifiTimer.setInterval(callback, WIFI_CHECK_INTERVAL);
}

void WifiAsyncConnect::wifi_async_check() {
    if (!is_all_wifi_checked) {
        wifiTimer.handle();
    } else {
        if (!is_finished) {
            is_finished = true;
            Serial.print("all wifi checked,");
            if (is_wifi_success) {
                Serial.println("wifi connect succeed");
            } else {
                Serial.println("wifi connect failed");
            }
            wifiTimer.cancel(timer_id);
            is_timer_checked = true;
        }
    }
}

void WifiAsyncConnect::wifi_close() {
    WiFi.disconnect(true);  //禁用wifi
    is_wifi_success = false;
    Serial.println("wifi closed");
}

bool WifiAsyncConnect::get_wifi_status() {
    return is_all_wifi_checked && is_wifi_success;
}